package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.GoodsFeeInfoVO;
import com.iwhalecloud.bss.kite.cucc.common.util.AssemblyAttrDtoUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferAttrCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Product;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.service.util.CopyToDtoUtil;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;
import com.ztesoft.bss.base.staticdata.CoreDataProduct;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品信息
 */
@Service
public class GoodsAttrInfoModuleHandler extends AbstractModuleHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private OperateInstAttrService operateInstAttrService;

    @Override
    public List<GoodsFeeInfoVO> execute(AcceptContext context, SceneModule sceneModule) {
        String offerId = context.getAcceptRequest().getOfferId();
        String sceneInstId = context.getSceneVo().getSceneInstId();

        Map<String, List<InstAttrDTO>> result = new LinkedHashMap<>(); //返回值

        List<InstAttrDTO> buziInfoList = new ArrayList<>(); //业务信息

        List<InstAttrDTO> feeInfoList = new ArrayList<>(); //资费信息

        List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);
        kiteProdInsts.forEach(kiteProdInst -> {
            Product product = ProductCache.get(kiteProdInst.getProdId());
            if (KiteStringUtils.equals(product.getBillProdType(), CoreDataProduct.PRD_C_0001_1000)) {
                //展示关键属性
                List<InstAttrDTO> accessProdInstAttr = CopyToDtoUtil.transInstAttrDtoList(kiteProdInst.listAttrs());
                //accessProdInstAttr.forEach(instAttrDTO -> instAttrDTO.setIsEdit("F"));
                accessProdInstAttr.forEach(instAttrDTO -> {
                	String fieldName = instAttrDTO.getFieldName();
                	if (KeyConsts.DROPDOWN.equals(instAttrDTO.getAttrValueTypeId()) && KiteListUtils.isNotEmpty(instAttrDTO.getAttrValues()) && instAttrDTO.getAttrValues().size() == 2) {
                		String value = instAttrDTO.getAttrValues().stream().filter((attr) -> !KiteStringUtils.isEmpty(attr.getAttrValue())).collect(Collectors.toList()).get(0).getAttrValue();
                        instAttrDTO.setValue(value);
                        instAttrDTO.setValueDesc(instAttrDTO.getAttrValues().stream().filter((attr) -> !KiteStringUtils.isEmpty(attr.getAttrValue())).collect(Collectors.toList()).get(0).getAttrValueDesc());

                        operateInstAttrService.setAttrValue(kiteProdInst, fieldName, value, sceneInstId, null);
                	}
                });
                accessProdInstAttr.removeIf(instAttrDTO -> !KeyConsts.PROD_ATTR_SHOW_TYPE_D.equals(instAttrDTO.getShowType()));
                buziInfoList.addAll(accessProdInstAttr);
            }
            else {
                //展示特定属性
                List<InstAttrDTO> instAttrList = CopyToDtoUtil.transInstAttrDtoList(kiteProdInst.listAttrs());
                feeInfoList.addAll(dealBillAttr(instAttrList, sceneInstId, kiteProdInst));
                sortAttr(feeInfoList);
            }
        });

        result.put("业务信息", buziInfoList);
        result.put("资费信息", feeInfoList);

        GoodsFeeInfoVO feeInfo = new GoodsFeeInfoVO();
        /* 重复展示，这里先注释掉
        feeInfo.setAttrInfo(result);
        feeInfo.setModuleName(OfferCache.get(offerId).getOfferName());

        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        sceneNewOfferSeneVO.setGoodsFeeInfo(feeInfo);*/

        return Collections.singletonList(feeInfo);
    }


    @Override
    public List<ModuleVO> previewSceneVo(AcceptContext context, SceneModule sceneModule) {
        String sceneInstId = context.getSceneVo().getSceneInstId();

        Map<String, List<InstAttrDTO>> result = new LinkedHashMap<>(); //返回值
        List<InstAttrDTO> buziInfoList = new ArrayList<>(); //业务信息
        List<InstAttrDTO> feeInfoList = new ArrayList<>(); //资费信息
        List<KiteProdInst> kiteProdInsts = querySceneInstService.listProdInsts(sceneInstId);

        kiteProdInsts.forEach(kiteProdInst -> {
            Product product = ProductCache.get(kiteProdInst.getProdId());
            List<InstAttrDTO> attrList = AssemblyAttrDtoUtils.assemblyInstAttr(kiteProdInst.listAttrs());
            if (KiteStringUtils.equals(product.getBillProdType(), CoreDataProduct.PRD_C_0001_1000)) {
                // 预览需展示全部属性
                //展示关键属性
//                attrList.removeIf(instAttrDTO -> !KeyConsts.PROD_ATTR_SHOW_TYPE_D.equals(instAttrDTO.getShowType()));
                buziInfoList.addAll(attrList);
            }
            else {
                //展示特定属性
                feeInfoList.addAll(attrList);
            }
        });

        result.put("业务信息", buziInfoList);
        result.put("资费信息", feeInfoList);
        GoodsFeeInfoVO feeInfo = new GoodsFeeInfoVO();
        //        feeInfo.setAttrInfo(result);
        //        feeInfo.setModuleName(OfferCache.get(context.getAcceptRequest().getOfferId()).getOfferName());
        //        SceneNewOfferSeneVO sceneNewOfferSeneVO = (SceneNewOfferSeneVO) context.getSceneVo();
        //        sceneNewOfferSeneVO.setGoodsFeeInfo(feeInfo);

        return Collections.singletonList(feeInfo);
    }

    private Map<String, Integer> getSortMap() {
        //单价 生效时间 失效时间 生效模式 失效模式
        Map<String, Integer> sortMap = new HashMap<>();
        sortMap.put("200001648", 1);
        sortMap.put("200000172", 2);
        sortMap.put("200000173", 3);
        sortMap.put("200000174", 4);
        sortMap.put("200001735", 5);
        return sortMap;
    }

    /**
     * 排序
     * @param attrList
     */
    private void sortAttr(List<InstAttrDTO> attrList) {
        Map<String, Integer> sortMap = getSortMap();
        attrList.sort((o1, o2) -> {
            int sortNum1 = 99;
            if (sortMap.containsKey(o1.getFieldName())) {
                sortNum1 = sortMap.get(o1.getFieldName());
            }
            int sortNum2 = 99;
            if (sortMap.containsKey(o2.getFieldName())) {
                sortNum2 = sortMap.get(o2.getFieldName());
            }
            return Integer.compare(sortNum1, sortNum2);
        });
    }

    /**
     * 处理属性
     * @param instAttrList
     * @param sceneInstId
     * @param kiteProdInst
     * @return
     */
    private List<InstAttrDTO> dealBillAttr(List<InstAttrDTO> instAttrList, String sceneInstId, KiteProdInst kiteProdInst) {
        Map<String, Integer> sortMap = getSortMap();
        List<InstAttrDTO> feeAttrList = new ArrayList<>();
        instAttrList.forEach(instAttrDTO -> {
            String fieldName = instAttrDTO.getFieldName();
            if (sortMap.containsKey(fieldName)) {
                instAttrDTO.setIsEdit("F");
                if (StringUtils.isEmpty(instAttrDTO.getValue())) {
                    String value = instAttrDTO.getValue();
                    String valueDesc = instAttrDTO.getValueDesc();
                    if ("200001648".equals(fieldName)) {
                        KiteOfferInst offerInst =  querySceneInstService.getMainOfferInst(sceneInstId);
                        List<OfferAttr> offerAttrs = OfferAttrCache.get(offerInst.getOfferId());
                        for (OfferAttr offerAttr : offerAttrs) {
                            if ("price".equals(offerAttr.getFieldName())) {
                                value = offerAttr.getDefaultValue();
                                valueDesc = value;
                                break;
                            }
                        }

                    }
                    else if ("200000172".equals(fieldName)) {
                        value = DateUtils.formatDate(DateUtils.getStartOfDay(), DateUtils.DEFAULT_PATTERN);
                        valueDesc = value;
                    }
                    else if ("200000173".equals(fieldName)) {
                        value = DateUtils.formatDate(DateUtils.getEndOfDay(), DateUtils.DEFAULT_PATTERN);
                        valueDesc = value;
                    }
                    else if (KeyConsts.DROPDOWN.equals(instAttrDTO.getAttrValueTypeId()) && KiteListUtils.isNotEmpty(instAttrDTO.getAttrValues())) {
                        value = instAttrDTO.getAttrValues().stream().filter((attr) -> !KiteStringUtils.isEmpty(attr.getAttrValue())).collect(Collectors.toList()).get(0).getAttrValue();
                        valueDesc = instAttrDTO.getAttrValues().stream().filter((attr) -> !KiteStringUtils.isEmpty(attr.getAttrValue())).collect(Collectors.toList()).get(0).getAttrValueDesc();
                    }
                    instAttrDTO.setValue(value);
                    instAttrDTO.setValueDesc(valueDesc);

                    operateInstAttrService.setAttrValue(kiteProdInst, fieldName, value, sceneInstId, null);
                }
                feeAttrList.add(instAttrDTO);
            }
        });

        return feeAttrList;


    }

}
